#include <iostream>
#include <string>
#include <unordered_map>
#include <muduo/net/TcpServer.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/Buffer.h>
#include <muduo/net/EventLoop.h>

class DictServer
{
private:
    muduo::net::EventLoop _baseloop;
    muduo::net::TcpServer _server;
private:
    // 回调方法
    void onConnectionCallback(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected())
        {
            std::cout << "连接建立" << std::endl;
        }
        else 
        {
            std::cout << "连接关闭" << std::endl;
        }
    }
    void onMessageCallback(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buf,
    muduo::Timestamp)
    {
        std::string res;
        std::string msg = buf->retrieveAllAsString();
        std::unordered_map<std::string, std::string> dict = {
            {"hello", "你好"},
            {"world", "世界"}
        };
        auto it = dict.find(msg);
        if(it != dict.end())
        {
            res = it->second;
        }
        else 
        {
            res = "未知单词";
        }
        std::cout << msg << std::endl;
        conn->send(res);
    }
public:
    DictServer(int port)
    :_server(&_baseloop, muduo::net::InetAddress("0.0.0.0", port), "DictServer", muduo::net::TcpServer::kReusePort)
    {
        _server.setConnectionCallback(std::bind(&DictServer::onConnectionCallback, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&DictServer::onMessageCallback, this, 
        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }
    void Start()
    {
        _server.start(); //启动
        _baseloop.loop(); //事件监控
    }
};

int main()
{   
    DictServer ds(9090);
    ds.Start();
    return 0;
}